<?php
/**
 * Created by PhpStorm.
 * User: qzy008
 * Date: 2018/9/7
 * Time: 17:32
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\model\Admin as AdminModel;
use app\api\service\AdminToken;
use app\api\service\Token as TokenService;
use app\api\validate\admin\AdminCreateOrEdit;
use app\api\validate\admin\Login as LoginValidate;
use app\lib\exception\LockedException;
use app\lib\exception\ParameterException;
use app\lib\exception\TokenException;

class Admin extends BaseController
{
    public function createAdmin()
    {
        $validate = new AdminCreateOrEdit();
        $validate->goCheck(['scene' => 'create']);
        $params = $validate->getParameters();
        $result = AdminModel::createAdmin($params);
        return $this->returnHandle($result);
    }

    public function deleteAdmin($id)
    {
        $result = AdminModel::deleteAdmin($id);
        return $this->returnHandle($result);
    }

    public function updateAdmin()
    {
        $validate = new AdminCreateOrEdit();
        $validate->goCheck();
        $params = $validate->getParameters();
        $result = AdminModel::updateAdmin($params);

        return $this->returnHandle($result);
    }

    public function allAdmin()
    {
        return AdminModel::all();
    }

    public function login()
    {
        $validate = new LoginValidate();
        $validate->goCheck();
        $params = $validate->getParameters();
        $admin = AdminModel::readAdminByPassAccount($params);
        if (!$admin) {
            throw new ParameterException([
                'msg' => '账号或密码错误'
            ]);
        }
        // 判断用户是否锁定
        if ($admin['status'] == 0) {
            throw new LockedException();
        }
        $token = (new AdminToken())->grantToken($admin);
        return $this->returnHandle([
            'token' => $token
        ]);
    }

    public function getAdminInfo()
    {
        $adminID = TokenService::getCurrentTokenAdminID();
        $admin = AdminModel::getAdminInfoByID($adminID);

        $result = [
            'admin' => $admin
        ];
        return $this->returnHandle($result);
    }

    public function logout()
    {
        $result = TokenService::clearTokenCache();
        if (!$result) {
            throw new TokenException();
        }
        return $this->returnHandle($result);
    }
}